package com.iweb.tmall.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/*
* Page 页面身份拦截器
* 用户请求页面，并不是ajax发起的请求，而是浏览器发起的，没法操作报文参数和报文头
*身份令牌只能从cookie中拿，因为只有cookie是每次请求，自动携带到请求头
*后端还是从session拿令牌
* */
public class PageAuthInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("进入拦截器");
        /*HttpSession session = request.getSession();
        String localAuth = (String)session.getAttribute("Auth");
        System.out.println("session令牌"+localAuth);*/
        Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("Auth".equals(cookie.getName())){
                    /*System.out.println("cookie名" + cookie.getName());
                     System.out.println("cookie值" + cookie.getValue());*/
                    String remoteAuth = cookie.getValue();
                    String localAuth = stringRedisTemplate.opsForValue().get(remoteAuth);
                    if (remoteAuth.equals(localAuth)) {
                        return true;
                    }

            }
            }

        //通知浏览器重定向请求到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}
